var express = require('express');
var router = express.Router();
var _ = require('underscore');
var sha1 = require('../utils/sha1.js');
var nodegrass = require('nodegrass');
var URL = require('url');
var rest = require('rest');


function getToken(req, res, callback){
    var url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx3a50d2f115fd3e3f&secret=9fa472a01bee7b67df2cf0868774a736";

    nodegrass.get(url, function(data,status,headers){
        token = JSON.parse(data).access_token
        console.log("token:" + token);

        url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi";

        req.session.token = token;
        nodegrass.get(url, function(data,status,headers){
            ticket = JSON.parse(data).ticket
            console.log("tickets:" + ticket);
            req.session.ticket = ticket;
            req.session.startTime = Date.now();

            var noncestr = getNoncestr();
            var timestamp = getTimeStamp();
            var url = getUrl(req);

            var signature = getSignature(noncestr, timestamp, url, ticket);

            console.log('timestamp:'+timestamp);
            console.log('nonce:'+noncestr);
            console.log('signature:'+signature);
            console.log('url:'+url);
            console.log('tmpStr:'+tmpStr);

            callback(timestamp, noncestr, signature);
        },'utf8').on('error', function(e) {
            console.log("Got error: " + e.message);
        });

    },'utf8').on('error', function(e) {
        console.log("Got error: " + e.message);
    });
}

function getTicket(){
    token = getToken()
    if(!token){
        return
    }
    var url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi";

    data = null;
    nodegrass.get(url, function(data,status,headers){
        console.log("ticket" + JSON.parse(data).ticket);
        data = JSON.parse(data).ticket
    },'utf8').on('error', function(e) {
        console.log("Got error: " + e.message);
    });
    return data;
}

function getNoncestr(){
    return Math.random().toString(36).substr(2); // 生成随机字符串
}

function getTimeStamp(){
    return parseInt(Date.now().toString().substring(0, 10));
}

function getUrl(req){
    return "http://www.wpax.cn" + req.originalUrl;   
}

function getSignature(noncestr, timestamp, url, ticket){
    console.log('timestamp:'+timestamp);
    console.log('nonce:'+noncestr);
    console.log('url:'+url);

    var tmpArr = ["noncestr="+noncestr, "timestamp="+timestamp, "url="+url, "jsapi_ticket="+ticket];
    tmpStr = tmpArr.sort().join("&");
    console.log("signature str:" + tmpStr);
    var signature = sha1(tmpStr)
    return signature
}

// 谜语
router.get('/riddle/:id', function (req, res, next) {
    var id = req.params.id;
    ticket = req.session.ticket;
    startTime = req.session.startTime;
    currentTime = Date.now();

    time = currentTime - startTime;

    var riddle = null
    var riddle = function (timestamp, noncestr, signature){
        res.render("weixin/riddle/riddle", {
            title: "猜谜语",
            timestamp:timestamp,
            nonceStr:noncestr,
            signature:signature
        });
    }
    var riddle1 = function (timestamp, noncestr, signature){ // 活动一
        res.render("weixin/riddle/riddle1", {
            title: "夜半歌声，你和女鬼的缘分如何！雄鲸科技10台kindle等你拿！",
            timestamp:timestamp,
            nonceStr:noncestr,
            signature:signature
        });
    }
    if(id == 1){
        riddle = riddle1
    }
    if(!ticket || time > 1.5*60*60){
        console.log("get ticket");
        getToken(req, res, riddle);  
    }else{
        console.log("sessionticket");
        console.log("ticket"+ticket);
        var noncestr = getNoncestr();
        var timestamp = getTimeStamp();
        var url = getUrl(req);
        var signature = getSignature(noncestr, timestamp, url, ticket);
        riddle(timestamp, noncestr, signature);
    }
});

router.get('/riddle/result/:id', function(req, res, next){ // 测试结果
    var id = req.params.id;
    ticket = req.session.ticket
    startTime = req.session.startTime;
    currentTime = Date.now();
    time = currentTime - startTime;

    console.log("result page:" + id)

    var result = function(){
        res.render("weixin/riddle/result1", {
            title: "夜半歌声，你和女鬼的缘分如何！雄鲸科技10台kindle等你拿！测试结果!",
            timestamp:timestamp,
            nonceStr:noncestr,
            signature:signature
        });
    }
    if(!ticket || time > 1.5*60*60){
        getToken(req, res, result);  
    }else{
        var noncestr = getNoncestr();
        var timestamp = getTimeStamp();
        var url = getUrl(req);
        var signature = getSignature(noncestr, timestamp, url, ticket);
        result(timestamp, noncestr, signature);
    }
})

router.get('/topics', function(req, res, next){
    console.log('tttt');
    var menu = req.query.menu;
    console.log(menu);
    if (!menu) return;
    var url = 'http://data.wpax.cn/api/resource/WeiXinTopic?criteria={"menu":{"eq":"' + menu + '"}}';
    rest(url).then(function(data){
        console.log(data);
        var data = JSON.parse(data.entity);
        console.log(data);
        var list = data.page;
        res.render('weixin/topics', {
            list:list
        })
    });
})

var token = 'wpax';
router.get('/checkSignature', function (req, res, next) {
    var echostr = req.query.echostr;
    var signature = req.query.signature;
    var timestamp = req.query.timestamp;
    var nonce = req.query.nonce;

    var tmpArr = [token, timestamp, nonce]
    tmpStr = tmpArr.sort().join("")

    shaStr = sha1(tmpStr)
    console.log('signature:'+signature);
    if(shaStr == signature){
        console.log("success echostr:"+echostr)
        res.send(echostr);
    }else{
        console.log("error:"+echostr)
        res.send("errortest");
    }
});

module.exports = router;